#!/bin/bash

BASE=$(cd '..' && pwd)

example=$1

SOURCE=$BASE/examples/$example

if [ ! -d $SOURCE ]
then
	echo Example "$1" not found
else
	BUILD=$BASE/scripts/tmp/$example
	OUTPUT=$BASE/output/$example
	mkdir $OUTPUT $BUILD $BUILD/worksheet $BUILD/answer-key
	sed -e "s|@DIR|$BASE/include|" $BASE/include/head.tex > $BUILD/worksheet/worksheet.lytex
	sed -e "s|@DIR|$BASE/include|" $BASE/include/head.tex > $BUILD/answer-key/answer-key.lytex
	cat $SOURCE/$example >> $BUILD/worksheet/worksheet.lytex
	cat $SOURCE/$example >> $BUILD/answer-key/answer-key.lytex
	
	for ily in $(ls $SOURCE/*.ily); do
		name=$(basename $ily .ily)
		cat $BASE/include/head.ily $BASE/include/no-answers.ily $SOURCE/$name.ily > $BUILD/worksheet/$name.ly
		cat $BASE/include/head.ily $SOURCE/$name.ily > $BUILD/answer-key/$name.ly
		sed -e "s|@$name|\\\\lilypondfile[quote,noindent]\{$name.ly\}|g" -i $BUILD/worksheet/worksheet.lytex
		sed -e "s|@$name|\\\\lilypondfile[quote,noindent]\{$name.ly\}|g" -i $BUILD/answer-key/answer-key.lytex
	done;
	
	cat $BASE/include/tail.tex >> $BUILD/worksheet/worksheet.lytex
	cat $BASE/include/tail.tex >> $BUILD/answer-key/answer-key.lytex
	cd $BUILD/worksheet && lualatex --shell-escape worksheet.lytex
	cd $BUILD/answer-key && lualatex --shell-escape answer-key.lytex
	
	cp $BUILD/worksheet/worksheet.pdf $BUILD/answer-key/answer-key.pdf $OUTPUT
	
	id=$(grep $name.ly $BUILD/answer-key/tmp-ly/answer-key.list | awk 'END {print $1}')
	timidity -OF $BUILD/answer-key/tmp-ly/$id.midi
	cp $BUILD/answer-key/tmp-ly/$id.flac $OUTPUT/$name.flac
fi
